#include <avr/interrupt.h>
#include <avr/io.h>
#include "common.h"
#include "app.h"
#include "led.h"

volatile unsigned int pulse_width=0;

#define IS_PIND1_HIGH() 		(PORTD|= (_BV(PIND1)))

#define  duty_opened	1100 //2000
#define  duty_closed	2000 //1100


void init_global(){
	
    /** Disable default prescaler to make processor speed 8 MHz. */
    CLKPR = (1<<CLKPCE);
    CLKPR = 0x00;	


	//BEGIN Servo Motor
	DDRC |= (1<<PORTC5); //Enable output for PSWM

	TCCR3B = (0<<CS30) | (1<<CS31) | (0<<CS32) | (1<<WGM33) | (1<<WGM32); 
	TCCR3A = (0<<WGM30) | (1<<WGM31) | (1<<COM3B1) | (0<<COM3B0);

	ICR3 = 40000; // The max width for the PWM (TOP)
	OCR3B = duty_closed;
	//END Servo Motor

	//BEGIN IR-SENSOR
	PORTE |= (PORTE1 | PORTE3);
	//END IR-SENSOR

	init_LED_D2();
	init_LED_D5();

	sei(); /** enable global interrupts **/
}

int main(){

	

	init_global();

	//OCR3B = duty_opened;


	while(1){
		
		if(PINE & (_BV(PORTE3)))	// pin is high - no interruption
		{
			on_LED(LED_D2_GREEN);
			off_LED(LED_D2_RED);
		}
		else	// pin is low - interruption detected
		{
			off_LED(LED_D2_GREEN);
			on_LED(LED_D2_RED);
			OCR3B = duty_opened;
			
		}

		if(PINE & (_BV(PORTE1)))	// pin is high - no interruption
		{
			on_LED(LED_D5_GREEN);
			off_LED(LED_D5_RED);
		}
		else	// pin is low - interruption detected
		{
			off_LED(LED_D5_GREEN);
			on_LED(LED_D5_RED);
			OCR3B = duty_closed;			
		}

	}

}
